package org.example.优先级队列合并多个有序链表;


import org.example.ListNode;
import org.example.Priority;
import org.example.Queue;

import java.util.List;

/**
 * 小顶堆实现
 */
public class MinHead {

    ListNode[] array;
    int size;

    public MinHead(int capacity) {
        array = new ListNode[capacity];
    }

    public boolean offer(ListNode e) {
        if (isFull()) {
            return false;
        }
        int child = size++;
        int parent = (child -1)  / 2;
        while (child > 0 && e.val < array[parent].val) {
            array[child] = array[parent];
            child = parent;
            parent = (child - 1) / 2;
        }
        array[child] = e;
        return true;
    }



    public ListNode poll() {
        if (isEmpty()) {
            return null;
        }
        // 交换
        swap(0, size - 1);
        size--;
        ListNode e = array[size];
        array[size] = null; // help GC
        // 下潜
        down(0);
        return e;
    }

    /**
     * 下潜
     * @param parent
     */
    private void down(int parent) {
        int left = 2 * parent +1;
        int right = left + 1;
        int min = parent;
        if(left < size && array[min].val > array[left].val) {
            min = left;
        }
        if(right < size && array[min].val > array[right].val) {
           min = right;
        }
        if (min != parent) {
            swap(min,parent);
            down(min);
        }
    }

    /**
     * 交换
     * @param i
     * @param j
     */
    protected void swap(int i, int j) {
        ListNode priority = array[i];
        array[i] = array[j];
        array[j] = priority;
    }


    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == array.length;
    }
}
